"""
代码优化器命令行接口
提供命令行工具来使用代码优化器
"""

import os
import sys
import json
import argparse
import logging
from typing import Dict, Any, List, Optional

from .core import CodeAnalyzer, CodeOptimizer

def setup_logging(verbose: bool = False) -> None:
    """
    设置日志
    
    Args:
        verbose: 是否输出详细日志
    """
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[logging.StreamHandler()]
    )

def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
    """
    加载配置
    
    Args:
        config_path: 配置文件路径
        
    Returns:
        配置字典
    """
    # 默认配置
    config = {
        "max_line_length": 100,
        "max_complexity": 10,
        "fix_long_lines": True,
        "remove_console_logs": True,
        "comment_instead_of_remove": True,
        "exclude_dirs": ["venv", "node_modules", ".git", "__pycache__", ".pytest_cache"],
        "exclude_files": [r".*\.min\.js$", r".*\.bundle\.js$"]
    }
    
    # 如果提供了配置文件，加载它
    if config_path and os.path.exists(config_path):
        try:
            with open(config_path, 'r') as f:
                user_config = json.load(f)
                config.update(user_config)
        except Exception as e:
            logging.error(f"加载配置文件失败: {e}")
    
    return config

def analyze_command(args: argparse.Namespace) -> int:
    """
    分析命令处理函数
    
    Args:
        args: 命令行参数
        
    Returns:
        退出码
    """
    setup_logging(args.verbose)
    config = load_config(args.config)
    
    analyzer = CodeAnalyzer(config)
    
    if os.path.isfile(args.path):
        # 分析单个文件
        result = analyzer.analyze_file(args.path)
        
        if args.output:
            # 将结果写入文件
            with open(args.output, 'w') as f:
                json.dump(result, f, indent=2)
        else:
            # 打印结果
            print(json.dumps(result, indent=2))
        
        # 如果有问题，返回非零退出码
        return 1 if result.get("issues") else 0
    
    elif os.path.isdir(args.path):
        # 分析目录
        results = []
        
        for root, _, files in os.walk(args.path):
            # 检查是否应该排除此目录
            exclude = False
            for exclude_dir in config.get("exclude_dirs", []):
                if exclude_dir in root.split(os.sep):
                    exclude = True
                    break
            
            if exclude:
                continue
            
            for file in files:
                file_path = os.path.join(root, file)
                
                # 检查文件扩展名
                _, ext = os.path.splitext(file)
                if ext.lower() not in ['.py', '.js', '.ts']:
                    continue
                
                # 检查是否应该排除此文件
                exclude = False
                for exclude_pattern in config.get("exclude_files", []):
                    if exclude_pattern.search(file):
                        exclude = True
                        break
                
                if exclude:
                    continue
                
                # 分析文件
                result = analyzer.analyze_file(file_path)
                results.append(result)
        
        if args.output:
            # 将结果写入文件
            with open(args.output, 'w') as f:
                json.dump(results, f, indent=2)
        else:
            # 打印结果摘要
            total_issues = sum(len(r.get("issues", [])) for r in results)
            print(f"分析了 {len(results)} 个文件，发现 {total_issues} 个问题")
            
            # 按问题类型分组
            issue_types = {}
            for result in results:
                for issue in result.get("issues", []):
                    issue_type = issue.get("type", "unknown")
                    if issue_type not in issue_types:
                        issue_types[issue_type] = 0
                    issue_types[issue_type] += 1
            
            print("\n问题类型统计:")
            for issue_type, count in sorted(issue_types.items(), key=lambda x: x[1], reverse=True):
                print(f"  {issue_type}: {count}")
        
        # 如果有问题，返回非零退出码
        return 1 if any(r.get("issues") for r in results) else 0
    
    else:
        logging.error(f"路径不存在: {args.path}")
        return 1

def optimize_command(args: argparse.Namespace) -> int:
    """
    优化命令处理函数
    
    Args:
        args: 命令行参数
        
    Returns:
        退出码
    """
    setup_logging(args.verbose)
    config = load_config(args.config)
    
    optimizer = CodeOptimizer(config)
    
    if os.path.isfile(args.path):
        # 优化单个文件
        result = optimizer.optimize_file(args.path)
        
        if args.output:
            # 将结果写入文件
            with open(args.output, 'w') as f:
                json.dump(result, f, indent=2)
        else:
            # 打印结果
            if "error" in result:
                logging.error(f"优化失败: {result['error']}")
                return 1
            
            changes = result.get("changes", [])
            if changes:
                print(f"优化了 {len(changes)} 个问题:")
                for change in changes:
                    print(f"  - 行 {change['line']}: {change['type']}")
            else:
                print("没有需要优化的问题")
        
        # 如果有错误，返回非零退出码
        return 1 if "error" in result else 0
    
    elif os.path.isdir(args.path):
        # 优化目录
        result = optimizer.optimize_directory(args.path)
        
        if args.output:
            # 将结果写入文件
            with open(args.output, 'w') as f:
                json.dump(result, f, indent=2)
        else:
            # 打印结果摘要
            if "error" in result:
                logging.error(f"优化失败: {result['error']}")
                return 1
            
            print(f"处理了 {result['files_processed']} 个文件")
            print(f"优化了 {result['files_optimized']} 个文件")
            print(f"修复了 {result['total_issues_fixed']} 个问题")
            print(f"剩余 {result['total_issues_remaining']} 个问题")
            
            # 打印每个文件的变更
            if args.verbose:
                for file_result in result.get("file_results", []):
                    if file_result.get("changes"):
                        print(f"\n文件: {file_result['file_path']}")
                        for change in file_result.get("changes", []):
                            print(f"  - 行 {change['line']}: {change['type']}")
        
        # 如果有错误，返回非零退出码
        return 1 if "error" in result else 0
    
    else:
        logging.error(f"路径不存在: {args.path}")
        return 1

def main() -> int:
    """
    主函数
    
    Returns:
        退出码
    """
    parser = argparse.ArgumentParser(description="代码优化器")
    parser.add_argument("--version", action="version", version="代码优化器 v0.1.0")
    
    subparsers = parser.add_subparsers(dest="command", help="子命令")
    
    # 分析命令
    analyze_parser = subparsers.add_parser("analyze", help="分析代码")
    analyze_parser.add_argument("path", help="要分析的文件或目录路径")
    analyze_parser.add_argument("--config", help="配置文件路径")
    analyze_parser.add_argument("--output", help="输出文件路径")
    analyze_parser.add_argument("--verbose", "-v", action="store_true", help="输出详细日志")
    
    # 优化命令
    optimize_parser = subparsers.add_parser("optimize", help="优化代码")
    optimize_parser.add_argument("path", help="要优化的文件或目录路径")
    optimize_parser.add_argument("--config", help="配置文件路径")
    optimize_parser.add_argument("--output", help="输出文件路径")
    optimize_parser.add_argument("--verbose", "-v", action="store_true", help="输出详细日志")
    
    args = parser.parse_args()
    
    if args.command == "analyze":
        return analyze_command(args)
    elif args.command == "optimize":
        return optimize_command(args)
    else:
        parser.print_help()
        return 1

if __name__ == "__main__":
    sys.exit(main())